# 
# 
# 
# 
# 
# 
# 
# 
# 
# 
import tornado.ioloop
import tornado.web
import tornado.httpserver

import sys
import json
import httplib,urllib2

class Reflector( ) :
	def __init__( self ):
		self.pendingCallDic = {}
		self.currentCallid = None
		self.applicationRequestHandler = None

	@staticmethod
	def getInstance():
		if not hasattr(Reflector, "_instance") :
			Reflector._instance = Reflector()
		return Reflector._instance	

	def reflect ( self, action, callid, dict ):
		#if self.pendingCallDic.get(callid) :
		#	raise ValueError, "repeat callid :"+callid+" of "+action
		#
		self.currentCallid = callid
		self.pendingCallDic[callid] = action

		if int(callid) < 0 :
			self.applicationRequestHandler.write("{code:'0', message:'invalid callid:"+callid+"'}")
			return

		actionHandler = (action + "ActionHandler")
		try:
			instance = globals()[actionHandler](self.applicationRequestHandler)
			instance.execute(dict)
		except :
			self.applicationRequestHandler.write("{code:'0', message:'invalid action:"+action+"'}")
			return

	def clearCurrentCall ( self ):
		del self.pendingCallDic[self.currentCallid]

# ========================================================================================
# 
# ========================================================================================
class BaseActionHandler( ) :	
	def __init__ (self, applicationRequestHandler) :
		self.applicationRequestHandler = applicationRequestHandler

	def execute(self, dict) :
		print('\n=================>> below are the request parameters:')
		for k in dict :
			print( "%s = %s" %(k, dict[k]) )
		print('\n')
		# connect DB


	def write (self, chunk) :
		self.applicationRequestHandler.write(chunk )
		
class GetUserDataActionHandler( BaseActionHandler ) :
	def execute(self, dict) :
		BaseActionHandler.execute(self, dict)
		self.write('parameters : '+str(dict));
		


class BuyItemActionHandler( BaseActionHandler ) :
	def execute(self, dict) :
		pass

# ========================================================================================
# 
# ========================================================================================
class ApplicationRequestHandler(tornado.web.RequestHandler) :
	def get(self):
		action = self.get_argument('action', 'default')
		callid = self.get_argument('callid', '-1')
		dict = self.request.arguments
		Reflector.getInstance().applicationRequestHandler = self
		Reflector.getInstance().reflect( action, callid, dict)

	def post(self):
		self.set_header("Content-Type", "text/plain")
		self.write("You wrote " + self.get_argument("message"))
	
	def initialize(self, database):
		self.database = database
		#self.write('dbname is '+database+", ")


def main ():
	application = tornado.web.Application([
		(r"/", ApplicationRequestHandler,dict(database='no')),
		])
	application.listen( 8888 )
	tornado.ioloop.IOLoop.instance().start( )

if __name__ == "__main__":
	main()
